<template>
     <el-form :inline="true" :model="form" label-width="auto" style="padding: 10px;">
        <el-form-item label="编码">
                  <el-input v-model="form.code" :disabled="action!='add'"/>
                </el-form-item>
        <el-form-item label="名称">
          <el-input v-model="form.name"/>
        </el-form-item>
       <el-form-item label="类别">
         <el-input v-model="form.category"/>
       </el-form-item>
       <el-form-item label="终端配置">
         <el-select v-model="form.profileCode" filterable remote reserve-keyword
                    placeholder="---请选择---"
                    :remote-method="queryProfileOptions"
                    :loading="loading">
           <el-option v-for="item in profileOptions" :key="item.value" :label="item.label" :value="item.value"/>
         </el-select>
       </el-form-item>
       <el-form-item label="通信网关">
         <el-select v-model="form.gatewayCode" filterable remote reserve-keyword
                    :remote-method="queryGatewayCodeOptions"
                    placeholder="---请选择---"
                    :loading="loading">
           <el-option v-for="item in gatewayOptions" :key="item.value" :label="item.label" :value="item.value"/>
         </el-select>
       </el-form-item>
       <el-form-item label="所属设备">
       <el-select v-model="form.deviceId" filterable remote
                  placeholder="---请选择---"
                  :remote-method="(w)=>queryDeviceOptions(w,null,null,formOptions.device)"
                  :loading="loading">
         <el-option v-for="item1 in formOptions.device.data" :key="item1.value" :label="item1.label" :value="item1.value"/>
       </el-select>
       </el-form-item>

        <el-form-item label="备注">
          <el-input v-model="form.remark"  style="width: 700px;"/>
        </el-form-item>
          <div style="text-align:center;margin: 10px auto;">
            <el-button type="primary" @click="handleAdd">保存</el-button>
            <el-button @click="handleCancel">取消</el-button>
          </div>
      </el-form>

  <el-divider />




  <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleTabClick">
    <el-tab-pane label="最新" name="first">
      <el-table :data="signals" style="width: 100%;">
        <el-table-column prop="code" label="编码" />
        <el-table-column prop="name" label="名称"  />
        <el-table-column prop="unit" label="单位"/>
        <el-table-column prop="value" label="当前值">
          <template #default="scope">
            <el-tooltip v-if="scope.row.alarmMsg&&scope.row.alarmMsg.length>0"
                        :content="scope.row.alarmMsg"
                        placement="bottom"
                        effect="light">
              <el-text type="danger">{{scope.row.value}}{{scope.row.unit}}</el-text>
            </el-tooltip>
            <el-text v-else-if="scope.row.value" type="primary">{{scope.row.value}}{{scope.row.unit}}</el-text>
            <el-text v-else>-</el-text>
          </template>
        </el-table-column>
      </el-table>
    </el-tab-pane>
    <el-tab-pane label="历史" name="second">
      <div id ="echart" style="width: 1000px;height:400px;"></div>
    </el-tab-pane>
    <el-tab-pane label="联动" name="three">
        <el-table :data="sceneList"
                  highlight-current-row
                  :empty-text="'没有数据'"
                  :stripe="false"
                  :row-key="row => row.id"
                  @current-change="handleSceneChange">
          <el-table-column prop="name" label="名称">
            <template v-slot="scope">
              {{scope.row.name}}
              <template v-if="!scope.row.terminalCode">
                <el-tag type="danger">继承</el-tag>
              </template>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" />
          <el-table-column prop="triggerExpress" label="触发表达式"/>
          <el-table-column prop="triggerExpress" label="联动">
            <template v-slot="scope">
              <div style="white-space: pre-wrap;">
              {{scope.row.alarmEnable?'告警;':''}}
              <template v-if="scope.row.actionEnable">
                <template v-for="(actionFlow,fi) in scope.row.actionFlow" :key="fi">
                  <template v-for="(action,ai) in actionFlow.actions">
                    {{action.name}}{{ai===actionFlow.actions.length-1?'':"➩"}}
                  </template>
                  {{fi===scope.row.actionFlow.length-1?'':';'}}
                </template>
              </template>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="状态">
            <template v-slot="scope">
              <el-button v-if="scope.row.status" link type="success" @click="handleChangeStatusScene(scope.row)">启用</el-button>
              <el-button v-else link type="danger" @click="handleChangeStatusScene(scope.row)">禁用</el-button>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template #default="scope">
              <el-button link type="primary" @click="handleEditScene(scope.row)">编辑</el-button>
              <el-button link type="primary" @click="handleRemoveScene(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      <div style="text-align: center; padding: 10px;">
        <el-button link style="color:#409EFF" @click="handleAddScene">
          <el-icon :size="20">
            <Plus />
          </el-icon>
        </el-button>
      </div>
          <div style="height: 20px;"></div>
    </el-tab-pane>
    <el-tab-pane label="告警" name="alarm">
      <el-table :data="alarmObj.data" style="width: 100%;">
        <el-table-column prop="id" label="事件ID" />
        <el-table-column prop="name" label="名称" />
        <el-table-column prop="startTime" label="时间"/>
        <el-table-column prop="confirmed" label="确认">
          <template #default="scope">
            {{scope.row.confirmed?'是':'否'}}
          </template>
        </el-table-column>
        <el-table-column prop="cleared" label="清除">
          <template #default="scope">
            {{scope.row.cleared?'是':'否'}}
          </template>
        </el-table-column>
        <el-table-column prop="additionalInfo" label="附加信息">
          <template #default="scope">
            <el-text type="danger">{{scope.row.additionalInfo}}</el-text>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <el-button link type="primary" @click="handleAlarmEdit(scope.row)">处理</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-model:size="alarmObj.query.pageSize" v-model:page="alarmObj.query.pageNum" :total="alarmObj.total" @pagination="loadAlarmList" />
    </el-tab-pane>
    <el-tab-pane label="事件" name="eventLog">
      <el-form :inline="true" label-width="auto" style="padding: 10px;">
        <el-form-item label="消息">
          <el-input v-model="sendMsg" style="width: 700px;"/>
          <el-button @click="handleSendMsg">发送</el-button>
        </el-form-item>

      </el-form>


      <el-table :data="eventLogObj.data" style="width: 100%;">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="事件ID" />
        <el-table-column prop="name" label="名称" />
        <el-table-column prop="tran.sceneName" label="场景" />
        <el-table-column prop="success" label="是否成功">
          <template #default="scope">
            <el-text v-if="scope.row.success" type="success">成功</el-text>
            <el-text v-else type="danger">失败</el-text>
          </template>
        </el-table-column>
        <el-table-column prop="eventTime" label="时间"/>
        <el-table-column prop="tran.actionType" label="动作类型"/>
        <el-table-column prop="remark" label="参数"/>
      </el-table>
      <pagination v-model:size="eventLogObj.query.pageSize" v-model:page="eventLogObj.query.pageNum" :total="eventLogObj.total" @pagination="loadEventLogList" />
    </el-tab-pane>
  </el-tabs>
  <dwin ref="sceneDialog" :width="860" :url="'/view/scene/edit.vue'" :title="'新增/编辑场景配置'" @onclose="handleCloseScene"></dwin>
  <dwin ref="alarmDialog" :width="1024" :url="'/view/alarm/edit.vue'" :title="'告警详情'" @onclose="handleAlarmClose"></dwin>
</template>
<script>
    import{reactive, ref,onUnmounted} from 'vue'
    import {add,edit,call} from '../../http/terminal.js'
    import {query} from '../../http/iot.js'
    import {info} from '../../http/profile.js'

    import Dwin from "../../component/dwin.vue";
    import {useDict,searchTable,tranTable,tranDict} from '../../http/options.js'
    import WeekPlan from "../../component/weekPlan.vue";
    import gateway from "../gateway/index.vue";
    import SenceEdit from "../scene/edit.vue";
    import {listForExec,remove as removeScene,changeStatus as changeStatusScene} from '../../http/scene.js'
    import useWebsocket from '../../public/websocket.js';
    import {list as queryAlarmList} from '../../http/alarm.js'
    import {list as queryEventLogList} from '../../http/event-log.js'
    import Pagination from "../../component/pagination.vue";
    const {ElMessage,ElMessageBox} = ElementPlus;
    export default {
      computed: {
        gateway() {
          return gateway
        }
      },
      components: {Pagination, Dwin,WeekPlan,SenceEdit},
        props:{
          initParams:Object
        },
        setup(props,context){
          const dict = ref({});
          const  profileOptions = ref([]);
          const  gatewayOptions = ref([]);
          const signals=ref([])
          const activeName = ref('first')
          const loading = ref(false);

          useDict(dict,'fluxData,storePolicy,alarmPolicy,sceneAction,sceneTrigger');
          const form=reactive({
              code:'',
              name:'',
              category:'',
              remark:'',
              deviceId:'',
              profileCode:'',
              gatewayCode:''
            })

          const sendMsg = ref('');




          const handleAdd = ()=>{
              if(action.value=='add'){
                add(form).then(res=> {
                  response(res,context)
                });
              }else{
                edit(form).then(res=> {
                  response(res,context)
                });
              }
          }


          const handleCancel = ()=>{
              context.emit('close',false)
          }
          const action = ref('edit');



          const handleClose1 = (data)=>{
            data.forEach(item=>{
              form.signalList.push(item);
            })
            selectFirstRow();

          }

          const queryProfileOptions = (w,id,pid)=>{
            loading.value = true;
            searchTable('profile',{w,id,pid}).then(res=>{
              profileOptions.value = res.data;
              loading.value = false;
            })

          }

          const queryGatewayCodeOptions = (w,id,pid)=>{
            loading.value = true;
            searchTable('gateway',{w,id,pid}).then(res=>{
              gatewayOptions.value = res.data;
              loading.value = false;
            })
          }

          const ws = useWebsocket('ws://'+window.location.hostname+env.baseURL+"/ws/stiot/"+utils.readCookie("SOLONID"));
          ws.on('message',data=>{

            const data2 = data.playload.terminals.filter((v,i)=>v.code===form.code)||[{}]
            signals.value.forEach(item=>{
              if(!data2[0].data.hasOwnProperty(item.code)){
                return;
              }
              item.value = data2[0].data[`${item.code}`]
              item.alarmMsg = data2[0].alarm[`${item.code}`]
            })
          })

          const  myChart = ref(null)
          // const sourceData = ref([])
          // const series = ref([])
          const types = ["FLOAT","LONG","SHORT","INTEGER","DOUBLE"]
          const loadSignal=()=>{

            if(!signals.value)return;
            const fields = signals.value.filter(item=>types.includes(item.fieldType)).map(item=>{return item.code})
            if(!fields||fields.length<=0){
              return;
            }
            let str = "from(bucket: \"stxx\")\n" +
                "  |> range(start: -1h)\n" +
                "  |> filter(fn: (r) => r[\"_measurement\"] == \""+form.profileCode+"\" and r[\"di\"]==\""+form.code+"\")\n" +
                "  |> filter(fn: (r) => contains(value:r[\"_field\"],set:"+JSON.stringify(fields)+" ))\n"+

                "  |> aggregateWindow(every: 60s, fn: mean, createEmpty: false)\n" +
                //"  |> fill(value: 0)\n"+
                "  |> yield(name: \"mean\")";
            query(str).then(res=>{
              const data = res.data;
              if(!data||data.length<=0)return;
              //排序
              data.sort((a, b) =>parseInt(a.ts) - parseInt(b.ts))
              //时间转换
              data.forEach(item=>{
                item.ts = moment(parseInt(item.ts)*1000).format("HH:mm:ss")
              })
              const row = fields.map((v,key)=>({[v]: null}));
              if(data&&data.length>0) {
                //数据集转换
                //const keys = Object.keys(data[0]).filter(item => item != 'ts');
                const keys = [...fields]
                keys.unshift('ts');
                const source = [keys];
                const itemBack = {}
                data.forEach((item, ri) => {
                  Object.assign(itemBack,item)
                  source.push([])
                  keys.forEach((key, ci) => {
                    source[source.length - 1][ci] = itemBack[key]?itemBack[key]:0;
                  })
                })
                const series = new Array(keys.length - 1).fill({type: 'line', showSymbol: false});
                myChart.value.setOption({
                  legend: {},
                  tooltip: {},
                  dataset: {source: source},
                  xAxis: {type: 'category'},
                  yAxis: {},
                  series: series
                });
              }
            })
          }



          onMounted(()=>{
            if(props.initParams){
              Object.assign(form,props.initParams)
              console.log(form)
              queryProfileOptions(null,form.profileCode,null)
              queryGatewayCodeOptions(null,form.gatewayCode,null)
              queryDeviceOptions(null,form.deviceId,null,formOptions.device)
              action.value= 'edit'
              info(form.profileCode).then(res=>{
                signals.value = res.data.data.signalList;

                ws.on('open',()=>{

                  ws.send({
                    command: "setPageModel",
                    params: {
                      terminals: [form.code],
                      queries: []
                    }
                  })
                })
                ws.connect();
                myChart.value = echarts.init(document.getElementById('echart'));
                loadSignal();
                loadScene();
                loadAlarmList();
                loadEventLogList();
                setInterval(()=>{
                  loadSignal();
                },5000)
              })

            }else{
              action.value= 'add'
            }
          })
          const handleTabClick = (tab, event)=>{
            // if(tab=='second'){
            //   myChart.value.resize();
            // }
          }

          onUnmounted(()=>{

          })

          //---------------------------------------
          //获取联动
          const sceneDialog = ref(null);
          const sceneList = ref([]);
          const loadScene =()=>{
            listForExec(form.profileCode,form.code).then(res=>{
              const data = ref(res.data);
              tranTable(data.value,{terminalCode:'terminal',profileCode:'profile'});
              tranDict(data.value,{triggerType:'sceneTrigger'},dict.value)
              sceneList.value = data.value;
            })
          }
          //新增联动
          const handleAddScene =()=>{
            const data = {
                id:'',
                name:'未命名场景',
                remark:'',
                triggerType:'TERMINAL',
                triggerExpress:'',
                profileCode:form.profileCode,
                terminalCode:form.code,
                signal:'',
                actionEnable:false,
                alarmEnable:false,
                planEnable:false,
                plan:[],
                alarmSetting:{
                  triggerMode:'CONTINUOS',
                  triggerValue:1,
                  detail:'',
                  autoClear:false,
                  clearMode:'CONTINUOS',
                  clearValue:1
                },
                actionFlow:[{actions:[{
                    name:'执行1',
                    actionType:'',
                    profileCode:'',
                    terminalCode:'',
                    delay:0,
                    params:''
                  }]}]
            }
            data.openByBusiness = true;
            sceneDialog.value.open(data);
          }
          const handleEditScene =(row)=> {
            if(!row.terminalCode){
              ElMessage.success("请到终端配置操作")
              return;
            }
            row.openByBusiness = true;
            sceneDialog.value.open(row);
          }



          //删除联动
          const handleRemoveScene =(row)=>{
            if(!row.terminalCode){
              ElMessage.success("请到终端配置操作")
              return;
            }
            let rows = ref([row]);
            beforeRemove(rows,()=>{
              removeScene(rows.value.map((item) => item.id).join()).then(res=>{
                if(response(res)){
                  loadScene()
                }
              })
            });
          }

          const handleChangeStatusScene=(row)=>{
            if(!row.terminalCode){
              ElMessage.success("请到终端配置操作")
              return;
            }
            changeStatusScene(row.id,!row.status).then(res=>{
              loadScene()
            })
          }


          //关闭对话框，刷新
          const handleCloseScene=()=>{
            loadScene()
          }
          //============================告警列表==============================
          const alarmDialog = ref(null)
          const  alarmObj = reactive({
            data:[],
            total:0,
            query:{
              pageSize:10,
              pageNum:1,
              cleared:false
            }
          })
          const loadAlarmList=()=>{
            queryAlarmList(Object.assign(alarmObj.query,{terminalCode:form.code})).then(res=>{
              alarmObj.data = res.data.data;
              alarmObj.total = parseInt(res.data.total);
            })
          }
          const handleAlarmEdit = (row)=>{
            alarmDialog.value.open(row);
          }
          const handleAlarmClose = ()=>{
            loadAlarmList()
          }
          //========================事件列表================================
          const  eventLogObj = reactive({
            data:[],
            total:0,
            query:{
              pageSize:10,
              pageNum:1
            }
          })
          const loadEventLogList=()=>{
            queryEventLogList(Object.assign(eventLogObj.query,{terminalCode:form.code})).then(res=>{
              eventLogObj.data = res.data.data;
              eventLogObj.total = parseInt(res.data.total);
            })
          }

          const handleSendMsg=()=>{
            call(form.code,sendMsg.value).then(res=>{
              loadEventLogList();
              ElMessage.success(res.data.msg)
            })
          }

//=======================设备Id=================
          const formOptions = ref({
            device:{data:[]}
          });
          const queryDeviceOptions=(w,id,pid,options,callback)=>{
            loading.value = true
            searchTable('device',{w,id,pid:pid}).then(res=>{
              console.log("bbbbbbbb",id)
              console.log("aaaaaaa",res)
              options.data = res.data;
              loading.value = false
              if(callback){
                callback(options.data);
              }
            })
          }

          return{
            form,handleAdd,handleCancel
            ,action,sceneDialog,handleClose1,dict
            ,queryProfileOptions,queryGatewayCodeOptions
            ,gatewayOptions,profileOptions,signals,activeName,handleTabClick
            ,sceneList,handleAddScene,handleRemoveScene
            ,handleChangeStatusScene,handleEditScene,handleCloseScene
            ,alarmObj,loadAlarmList,alarmDialog,handleAlarmEdit,handleAlarmClose
            ,eventLogObj,loadEventLogList
            ,sendMsg,handleSendMsg,queryDeviceOptions,loading,formOptions
          }
        }
    }
</script>

<style scoped>
.vertical-radio .el-radio {
  display: block;
  margin-bottom: 10px; /* 可根据需要调整间距 */
}
.header {
  font-size: 16px;
  border-top: #f0f0f0 solid 1px;
  margin: 0;
  box-shadow: 2px 2px 4px rgba(0,0,0,0.1);
}

.demo-tabs > .el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}



.el-form .el-select {
  width: 160px; /* 或者根据需要设置其他宽度 */
}
.el-form .el-input {
  width: 160px; /* 或者根据需要设置其他宽度 */
}
.vertical-radio .el-radio {
  display: block;
  margin: 0 0 10px 0; /* 可根据需要调整间距 */
}
.header {
  height: 50px;
  font-weight: bold;
  border-top: #f0f0f0 solid 1px;
  background-color: #f0f0f0;
  box-shadow: 2px 2px 4px rgba(0,0,0,0.1);
  margin-bottom: 10px;

}
.header .el-col{
  display:flex;align-items: center; padding-left: 10px;
}
.flex-grow {
  flex-grow: 1;
}
</style>